import {
  Delete as DeleteIcon,
  Edit as EditIcon,
  GridView as GridViewIcon,
  List as ListIcon,
} from "@mui/icons-material";
import {
  Box,
  Button,
  Card,
  CardActions,
  CardContent,
  CardMedia,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  ToggleButton,
  ToggleButtonGroup,
  Tooltip,
  Typography,
} from "@mui/material";
import { DataGrid } from "@mui/x-data-grid";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { filterImage } from "../App";
import { deletePost, getPosts } from "../services/api";

export default function Dashboard() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [viewMode, setViewMode] = useState("list");
  const [paginationModel, setPaginationModel] = useState({
    page: 0,
    pageSize: 10,
  });
  const [totalRows, setTotalRows] = useState(0);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedPost, setSelectedPost] = useState(null);
  const navigate = useNavigate();

  const loadPosts = async () => {
    try {
      setLoading(true);
      const response = await getPosts(
        paginationModel.page + 1,
        paginationModel.pageSize
      );
      // Transform the data to match our frontend structure
      const transformedPosts = response.records.map((post) => ({
        ...post,
        imageUrls: [
          post.imageUrl1,
          post.imageUrl2,
          post.imageUrl3,
          post.imageUrl4,
          post.imageUrl5,
        ].filter(Boolean),
      }));
      setPosts(transformedPosts);
      setTotalRows(parseInt(response.total));
    } catch (error) {
      toast.error(error.message || "Failed to load posts");
      console.error("Error loading posts:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadPosts();
  }, [paginationModel]);

  const handleEdit = (post) => {
    navigate(`/edit/${post.id}`, {
      state: {
        post: {
          content: post.content || "",
          imageUrls: [
            post.imageUrl1,
            post.imageUrl2,
            post.imageUrl3,
            post.imageUrl4,
            post.imageUrl5,
          ].filter(Boolean),
          customProfileUrl: post.customProfileUrl || "",
          customProfileName: post.customProfileName || "",
          isPremium: post.isPremium || false,
          memberName: post.memberName,
          memberId: post.memberId,
        },
      },
    });
  };

  const handleDeleteClick = (post) => {
    setSelectedPost(post);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    try {
      await deletePost(selectedPost.id);
      toast.success("Post deleted successfully");
      loadPosts();
    } catch (error) {
      toast.error(error.message || "Failed to delete post");
      console.error("Error deleting post:", error);
    } finally {
      setDeleteDialogOpen(false);
      setSelectedPost(null);
    }
  };

  const handleViewModeChange = (event, newMode) => {
    if (newMode !== null) {
      setViewMode(newMode);
    }
  };

  const GridView = () => (
    <Grid container spacing={3}>
      {posts.map((post) => (
        <Grid item xs={12} sm={6} md={4} lg={3} key={post.id}>
          <Card
            sx={{ height: "100%", display: "flex", flexDirection: "column" }}
          >
            <Box sx={{ px: 1, pt: 1 }}>
              {post.imageUrls && post.imageUrls.length > 0 ? (
                <Grid container spacing={1}>
                  {post.imageUrls.map((url, idx) => (
                    <Grid item xs={6} key={idx}>
                      <CardMedia
                        component="img"
                        image={filterImage(url, "200")}
                        alt={`Post image ${idx + 1}`}
                        sx={{
                          width: "100%",
                          height: "100px",
                          objectFit: "cover",
                          borderRadius: 1,
                        }}
                      />
                    </Grid>
                  ))}
                </Grid>
              ) : (
                <Box
                  sx={{
                    height: "100px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    bgcolor: "grey.200",
                  }}
                >
                  <Typography variant="body2" color="text.secondary">
                    No image
                  </Typography>
                </Box>
              )}
            </Box>
            <CardContent sx={{ flexGrow: 1 }}>
              <Tooltip title={post.content} enterDelay={500} arrow>
                <Typography
                  sx={{
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    display: "-webkit-box",
                    WebkitLineClamp: 4,
                    WebkitBoxOrient: "vertical",
                    cursor: "pointer",
                    minHeight: "5em",
                  }}
                >
                  {post.content}
                </Typography>
              </Tooltip>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                {post.customProfileName} {post.isPremium && "(Premium)"}
              </Typography>
              <Typography
                variant="caption"
                color="text.secondary"
                display="block"
              >
                {new Date(post.createTime).toLocaleDateString("en-US", {
                  year: "numeric",
                  month: "short",
                  day: "numeric",
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </Typography>
            </CardContent>
            <CardActions>
              <Button
                size="small"
                startIcon={<EditIcon />}
                onClick={() => handleEdit(post)}
              >
                Edit
              </Button>
              <Button
                size="small"
                color="error"
                startIcon={<DeleteIcon />}
                onClick={() => handleDeleteClick(post)}
              >
                Delete
              </Button>
            </CardActions>
          </Card>
        </Grid>
      ))}
    </Grid>
  );

  const columns = [
    { field: "id", headerName: "ID", width: 90 },
    {
      field: "content",
      headerName: "Content",
      width: 400,
      flex: 2,
      renderCell: (params) => (
        <Tooltip title={params.value} enterDelay={500} arrow>
          <Typography
            sx={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              display: "-webkit-box",
              WebkitLineClamp: 3,
              WebkitBoxOrient: "vertical",
              cursor: "pointer",
              py: 1,
            }}
          >
            {params.value}
          </Typography>
        </Tooltip>
      ),
    },
    {
      field: "imageUrls",
      headerName: "Images",
      width: 180,
      renderCell: (params) => (
        <Box sx={{ display: "flex", gap: 0.5, alignItems: "center" }}>
          {params.value.map((url, index) => (
            <Box
              key={index}
              sx={{
                width: 40,
                height: 40,
                borderRadius: 1,
                overflow: "hidden",
                flexShrink: 0,
              }}
            >
              <CardMedia
                component="img"
                image={filterImage(url, "80")}
                alt={`Image ${index + 1}`}
                sx={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                }}
              />
            </Box>
          ))}
        </Box>
      ),
    },
    {
      field: "isPremium",
      headerName: "Premium",
      width: 110,
      type: "boolean",
    },
    {
      field: "customProfileName",
      headerName: "Profile",
      width: 200,
      sortable: true,
      renderCell: (params) => (
        <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
          <Box
            sx={{
              width: 40,
              height: 40,
              borderRadius: "50%",
              overflow: "hidden",
              flexShrink: 0,
              bgcolor: "grey.200",
            }}
          >
            <CardMedia
              component="img"
              image={filterImage(
                params.row.customProfileUrl || "/default-avatar.png",
                "80"
              )}
              alt={params.row.customProfileName || "Profile"}
              sx={{
                width: "100%",
                height: "100%",
                objectFit: "cover",
              }}
            />
          </Box>
          <Typography>{params.row.customProfileName || "Anonymous"}</Typography>
        </Box>
      ),
    },
    {
      field: "createTime",
      headerName: "Created",
      width: 160,
      valueFormatter: (params) =>
        new Date(params.value).toLocaleDateString("en-US", {
          year: "numeric",
          month: "short",
          day: "numeric",
          hour: "2-digit",
          minute: "2-digit",
        }),
    },
    {
      field: "actions",
      headerName: "Actions",
      width: 200,
      renderCell: (params) => (
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            size="small"
            variant="outlined"
            onClick={() => handleEdit(params.row)}
            startIcon={<EditIcon />}
          >
            Edit
          </Button>
          <Button
            size="small"
            variant="outlined"
            color="error"
            onClick={() => handleDeleteClick(params.row)}
            startIcon={<DeleteIcon />}
          >
            Delete
          </Button>
        </Box>
      ),
    },
  ];

  return (
    <Box sx={{ height: "calc(100vh - 100px)", width: "100%" }}>
      <Box sx={{ display: "flex", justifyContent: "space-between", mb: 2 }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
          <Typography variant="h4" component="h1">
            Posts Management
          </Typography>
          <ToggleButtonGroup
            value={viewMode}
            exclusive
            onChange={handleViewModeChange}
            size="small"
          >
            <ToggleButton value="list" aria-label="list view">
              <ListIcon />
            </ToggleButton>
            <ToggleButton value="grid" aria-label="grid view">
              <GridViewIcon />
            </ToggleButton>
          </ToggleButtonGroup>
        </Box>
        <Button
          variant="contained"
          color="primary"
          onClick={() => navigate("/create")}
        >
          Create New Post
        </Button>
      </Box>

      {viewMode === "list" ? (
        <DataGrid
          rows={posts}
          columns={columns}
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[5, 10, 25]}
          rowCount={totalRows}
          loading={loading}
          disableRowSelectionOnClick
          sx={{
            "& .MuiDataGrid-cell": {
              whiteSpace: "normal",
              lineHeight: "normal",
              padding: "8px",
            },
          }}
        />
      ) : (
        <GridView />
      )}

      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>Confirm Delete</DialogTitle>
        <DialogContent>
          Are you sure you want to delete this post?
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
          <Button
            onClick={handleDeleteConfirm}
            color="error"
            variant="contained"
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
